package com.zhiqian.community.actuator;

import com.zhiqian.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Component
@Endpoint(id = "db")
public class DBEndpoint {
    private static final Logger logger=LoggerFactory.getLogger(DBEndpoint.class);

    @Autowired
    private DataSource dataSource;

    //@ReadOperation 表明此方法是通过get请求访问
    //@WriteOperation 表明此方法是通过post请求访问
    @ReadOperation
    public String checkConnection(){
        try(Connection connection = dataSource.getConnection();){
            return CommunityUtil.getJSONString(0,"数据库连接正常");
        }catch (SQLException e){
            logger.error("获取数据库连接失败："+e.getMessage());
            Map<String,Object> map=new HashMap<>();
            map.put("errorMessage",e.getMessage());
            return CommunityUtil.getJSONString(1,"数据库连接异常",map);
        }
    }
}
